<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="团队" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择团队" clearable>
          <el-option
            v-for="team in teamList"
            :key="team.teamId"
            :label="team.teamName"
            :value="team.teamId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成员姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入成员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="queryParams.roleId" placeholder="请选择角色" clearable>
          <el-option
            v-for="role in roleList"
            :key="role.roleId"
            :label="role.roleName"
            :value="role.roleId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable>
          <el-option label="活跃" :value="true" />
          <el-option label="非活跃" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="small"
          @click="handleAdd"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Plus /></el-icon>新增成员
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Edit /></el-icon>修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="成员姓名" align="center" prop="userName">
        <template #default="scope">
          <span v-if="scope.row.nickName">{{ scope.row.nickName }}</span>
          <span v-else-if="scope.row.userId">{{ getUserNickNames(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" prop="roleName" />
      <el-table-column label="加入时间" align="center" prop="joinDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.joinDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="isActive">
        <template #default="scope">
          <el-tag :type="scope.row.isActive === true ? 'success' : 'info'">
            {{ scope.row.isActive === true ? '活跃' : '非活跃' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:team:member:view']"
          >
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团队成员对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="团队" prop="teamId">
          <el-select v-model="form.teamId" placeholder="请选择团队" clearable :disabled="isView">
            <el-option
              v-for="team in teamList"
              :key="team.teamId"
              :label="team.teamName"
              :value="team.teamId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成员" prop="userIds">
          <el-select 
            v-model="form.userIds" 
            placeholder="请选择成员（可多选）" 
            clearable 
            multiple
            filterable
            :loading="userLoading"
            @focus="loadUsers"
            :disabled="isView"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            >
              <span style="float: left">{{ user.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.userName }}</span>
            </el-option>
          </el-select>
          <div class="el-form-item__help" style="color: #909399; font-size: 12px; margin-top: 4px;">
            支持多选，一次可以添加多个成员到团队中
          </div>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色" clearable :disabled="isView">
            <el-option
              v-for="role in roleList"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="加入时间" prop="joinDate">
          <el-date-picker clearable
            v-model="form.joinDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择加入时间"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="form.isActive" :disabled="isView">
            <el-radio :label="true">活跃</el-radio>
            <el-radio :label="false">非活跃</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs } from 'vue'
import type { FormInstance } from 'element-plus'
import { listTeamMember, getTeamMember, delTeamMember, addTeamMember, updateTeamMember } from "@/api/pm/team-member";
import { getTeamList as getTeamListApi } from "@/api/pm/team";
import { listUser } from "@/api/system/user";
import { listTeamRole } from "@/api/pm/team";
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import Pagination from '@/components/Pagination/index.vue';

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 获取字典数据
// const { pm_team_member_status } = toRefs<any>(proxy?.useDict('pm_team_member_status'))

// 表单引用
const formRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()

// 响应式数据
const loading = ref(true)
const userLoading = ref(false)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const memberList = ref<any[]>([])
const teamList = ref<any[]>([])
const userList = ref<any[]>([])
const roleList = ref<any[]>([])
const title = ref("")
const open = ref(false)
const isView = ref(false)

// 查询参数
const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  teamId: null,
  userName: null,
  roleId: null,
  isActive: null,
})

// 表单参数
const form = ref<any>({
  id: null,
  teamId: null,
  userIds: [],
  roleId: null,
  joinDate: null,
  isActive: true,
  remark: null
})

// 表单校验
const rules = reactive({
  teamId: [
    { required: true, message: "团队不能为空", trigger: "change" }
  ],
  userIds: [
    { required: true, message: "请至少选择一个成员", trigger: "change" }
  ],
  roleId: [
    { required: true, message: "角色不能为空", trigger: "change" }
  ]
})

// 生命周期
onMounted(async () => {
  // 先加载基础数据，再加载列表
  await getTeamList()
  await getUserList()
  await getRoleList()
  getList()
})

// 方法定义
/** 查询团队成员列表 */
const getList = () => {
  loading.value = true;
  listTeamMember(queryParams).then(response => {
    memberList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取成员列表失败:', error);
    memberList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 查询团队列表 */
const getTeamList = () => {
  return getTeamListApi({}).then(response => {
    teamList.value = response.rows || [];
  }).catch(error => {
    console.error('获取团队列表失败:', error);
    teamList.value = [];
  });
}

/** 查询用户列表 */
const getUserList = () => {
  return loadUsers();
}

/** 加载用户列表 */
const loadUsers = () => {
  userLoading.value = true;
  return listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    userList.value = response.rows || [];
    userLoading.value = false;
    console.log('用户列表加载完成:', userList.value);
    // 打印前几个用户的数据结构，帮助调试
    if (userList.value.length > 0) {
      console.log('第一个用户数据结构:', userList.value[0]);
      console.log('用户ID字段类型:', typeof userList.value[0].userId);
      console.log('用户ID字段值:', userList.value[0].userId);
    }
  }).catch(error => {
    console.error('获取用户列表失败:', error);
    userList.value = [];
    userLoading.value = false;
  });
}

/** 查询角色列表 */
const getRoleList = () => {
  return listTeamRole({}).then(response => {
    roleList.value = response.rows || [];
  }).catch(error => {
    console.error('获取角色列表失败:', error);
    roleList.value = [];
  });
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    teamId: null,
    userIds: [],
    roleId: null,
    joinDate: null,
    status: "1",
    remark: null
  };
  isView.value = false;
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.$nextTick(() => {
    queryFormRef.value?.resetFields();
  });
  handleQuery();
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加团队成员";
  isView.value = false;
}

/** 获取用户名称（处理多用户ID） */
const getUserNames = (userIdStr: string) => {
  if (!userIdStr) return '';
  console.log('getUserNames - userIdStr:', userIdStr);
  console.log('getUserNames - userList:', userList.value);
  
  // 保持字符串格式，避免大整数精度丢失
  const userIds = userIdStr.split(',').map(id => id.trim());
  console.log('getUserNames - userIds (字符串):', userIds);
  
  const names = userIds.map(id => {
    // 尝试多种匹配方式
    let user = userList.value.find(u => u.userId == id); // 使用 == 进行宽松比较
    if (!user) {
      user = userList.value.find(u => u.userId === String(id));
    }
    if (!user) {
      user = userList.value.find(u => String(u.userId) === String(id));
    }
    if (!user) {
      // 尝试Number匹配
      user = userList.value.find(u => Number(u.userId) === Number(id));
    }
    if (!user) {
      // 尝试BigInt匹配（处理大整数）
      try {
        user = userList.value.find(u => u.userId === BigInt(id));
      } catch (e) {
        // BigInt转换失败，忽略
      }
    }
    console.log(`getUserNames - 查找用户ID "${id}" (类型: ${typeof id}):`, user);
    return user ? user.userName : `用户${id}`;
  });
  console.log('getUserNames - names:', names);
  return names.join(', ');
}

/** 获取用户昵称（处理多用户ID） */
const getUserNickNames = (userIdStr: string) => {
  if (!userIdStr) return '';
  console.log('getUserNickNames - userIdStr:', userIdStr);
  console.log('getUserNickNames - userList:', userList.value);
  
  // 保持字符串格式，避免大整数精度丢失
  const userIds = userIdStr.split(',').map(id => id.trim());
  console.log('getUserNickNames - userIds (字符串):', userIds);
  
  // 打印用户列表中所有用户的ID，帮助调试
  console.log('用户列表中的所有用户ID:', userList.value.map(u => ({ userId: u.userId, nickName: u.nickName })));
  
  const names = userIds.map(id => {
    // 尝试多种匹配方式
    let user = userList.value.find(u => u.userId == id); // 使用 == 进行宽松比较
    if (!user) {
      user = userList.value.find(u => u.userId === String(id));
    }
    if (!user) {
      user = userList.value.find(u => String(u.userId) === String(id));
    }
    if (!user) {
      // 尝试Number匹配
      user = userList.value.find(u => Number(u.userId) === Number(id));
    }
    if (!user) {
      // 尝试BigInt匹配（处理大整数）
      try {
        user = userList.value.find(u => u.userId === BigInt(id));
      } catch (e) {
        // BigInt转换失败，忽略
      }
    }
    if (!user) {
      // 尝试将大整数ID转换为数字进行匹配（处理精度丢失的情况）
      const numId = parseInt(id);
      if (!isNaN(numId)) {
        user = userList.value.find(u => u.userId === numId);
      }
    }
    console.log(`getUserNickNames - 查找用户ID "${id}" (类型: ${typeof id}):`, user);
    return user ? user.nickName : `用户${id}`;
  });
  console.log('getUserNickNames - names:', names);
  return names.join(', ');
}

/** 查看按钮操作 */
const handleView = (row?: any) => {
  reset();
  const id = row?.id || ids.value[0]
  getTeamMember(id).then(response => {
    const memberData = response.data;
    console.log('查看时获取的成员数据:', memberData);
    
    // 将用户ID字符串转换为数组格式，用于多选组件显示
    let userIds = [];
    if (memberData.userId) {
      // 先尝试转换为数字，如果失败则保持字符串
      userIds = memberData.userId.split(',').map(id => {
        const trimmedId = id.trim();
        const numId = parseInt(trimmedId);
        // 检查转换后的数字是否与原字符串相等，避免精度丢失
        if (String(numId) === trimmedId) {
          return numId;
        } else {
          return trimmedId; // 保持字符串格式
        }
      });
    }
    
    console.log('查看时解析后的userIds:', userIds);
    
    form.value = {
      ...memberData,
      userIds: userIds
    };
    open.value = true;
    title.value = "查看团队成员";
    // 查看模式下禁用所有表单控件
    isView.value = true;
  });
}

/** 修改按钮操作 */
const handleUpdate = (row?: any) => {
  reset();
  const id = row?.id || ids.value[0]
  getTeamMember(id).then(response => {
    const memberData = response.data;
    console.log('修改时获取的成员数据:', memberData);
    
    // 将用户ID字符串转换为数组格式，用于多选组件
    let userIds = [];
    if (memberData.userId) {
      // 先尝试转换为数字，如果失败则保持字符串
      userIds = memberData.userId.split(',').map(id => {
        const trimmedId = id.trim();
        const numId = parseInt(trimmedId);
        // 检查转换后的数字是否与原字符串相等，避免精度丢失
        if (String(numId) === trimmedId) {
          return numId;
        } else {
          return trimmedId; // 保持字符串格式
        }
      });
    }
    
    console.log('解析后的userIds:', userIds);
    console.log('用户列表中的userId类型:', userList.value.length > 0 ? typeof userList.value[0].userId : 'unknown');
    
    form.value = {
      ...memberData,
      userIds: userIds
    };
    open.value = true;
    title.value = "修改团队成员";
    isView.value = false;
  });
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id != null) {
        // 修改成员
        updateTeamMember(form.value).then(response => {
          proxy?.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 添加成员（支持多用户）
        addTeamMember(form.value).then(response => {
          proxy?.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = (row?: any) => {
  const memberIds = row?.id ? [row.id] : ids.value
  proxy?.$modal.confirm('是否确认删除团队成员编号为"' + memberIds.join(',') + '"的数据项？').then(function() {
    return delTeamMember(memberIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
</script>